package com.xu.crawler.dao.impl;

import com.xu.crawler.dao.HistoryRecordDao;
import com.xu.crawler.dao.entity.HistoryRecordDO;
import com.xu.crawler.dao.entity.NewsDO;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * Created by clear on 2018/7/13.
 */
@Repository
public class HistoryRecordDaoImpl implements HistoryRecordDao {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public String queryLatestNewsUrl(Integer sourceId, String category) {
        Query query = new Query();
        query.addCriteria(Criteria.where("sourceId").is(sourceId));
        query.addCriteria(Criteria.where("category").is(category));
        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        query.limit(1);
        NewsDO target = mongoTemplate.findOne(query, NewsDO.class);
        return target == null ? null : target.getUrl();
    }

    @Override
    public void saveHistoryRecord(HistoryRecordDO historyRecordDO) {
        mongoTemplate.save(historyRecordDO);
    }
}
